//定义！
//方块
let picturePositionX = 0;
let picturePositionY = 0;
window.addEventListener('keydown', function (event){
  if (event.defaultPrevented) {
    return; // 如果事件已经在进行中，则不做任何事。
  }

    switch (event.key) {
    case "ArrowUp":
      picturePositionY--;
      console.log(picturePositionY + "up");
      // 按“↑”方向键时要做的事。
      break;
    case "ArrowDown":
      picturePositionY++;
      console.log(picturePositionY + "down");
      // 按“↓”方向键时要做的事。
      break;
    case "ArrowLeft":
      picturePositionX--;
      console.log(picturePositionX + "left");
      // 按“←”方向键时要做的事。
      break;
    case "ArrowRight":
      picturePositionX++;
      console.log(picturePositionX + "right");
      // 按“→”方向键时要做的事。
      break;
    case "Enter":
      // 按“回车”键时要做的事。
      break;
    case "Escape":
      // 按“ESC”键时要做的事。
      break;
    default:
      return; // 什么都没按就退出吧。
  }

  // 取消默认动作，从而避免处理两次。
  event.preventDefault();
}, true);

let drawsquare = () => {
  if (square.getContext) {
    let ctxsquare = square.getContext('2d');
    ctxsquare.clearRect(0, 0, 1000, 1000);
    ctxsquare.fillRect(25 + picturePositionX, 25 + picturePositionY, 100, 100);
    ctxsquare.clearRect(45 + picturePositionX, 45 + picturePositionY, 60, 60);
    ctxsquare.strokeRect(50 + picturePositionX, 50 + picturePositionY, 50, 50);
    requestAnimationFrame(drawsquare)
  }
}

//笑脸
let drawface = () => {
  if (simailu.getContext) {
    let ctxsimailu = simailu.getContext('2d');
    ctxsimailu.clearRect(0, 0, 1000, 1000);
    ctxsimailu.beginPath();
    ctxsimailu.arc(75 + picturePositionX, 75, 50, 0, Math.PI * 2, true);
    ctxsimailu.moveTo(110 + picturePositionX, 75 + picturePositionY);
    ctxsimailu.arc(75, 75, 35, 0, Math.PI, false);
    ctxsimailu.moveTo(65, 65);
    ctxsimailu.arc(60, 65, 5, 0, Math.PI * 2, true);
    ctxsimailu.moveTo(95, 65);
    ctxsimailu.arc(90, 65, 5, 0, Math.PI * 2, true);
    ctxsimailu.stroke();
    requestAnimationFrame(drawface)
  }
}

//太阳系
let sun = new Image();
let moon = new Image();
let earth = new Image();
let solarinit = () => {
  sun.src = 'image/sun.png';
  moon.src = 'image/moon.png';
  earth.src = 'image/earth.png';
  window.requestAnimationFrame(drawsolargalaxy);
}

let drawsolargalaxy = () => {
  let ctxsolar = document.getElementById('solargalaxy').getContext('2d');

  ctxsolar.globalCompositeOperation = 'destination-over';
  ctxsolar.clearRect(0, 0, 300, 300); // clear ballcanvas

  ctxsolar.fillStyle = 'rgba(0,0,0,0.4)';
  ctxsolar.strokeStyle = 'rgba(0,153,255,0.4)';
  ctxsolar.save();
  ctxsolar.translate(150, 150);

  // Earth
  let time = new Date();
  ctxsolar.rotate(((2 * Math.PI) / 60) * time.getSeconds() + ((2 * Math.PI) / 60000) * time.getMilliseconds());
  ctxsolar.translate(105, 0);
  ctxsolar.fillRect(0, -12, 50, 24); // Shadow
  ctxsolar.drawImage(earth, -12, -12);

  // Moon
  ctxsolar.save();
  ctxsolar.rotate(((2 * Math.PI) / 6) * time.getSeconds() + ((2 * Math.PI) / 6000) * time.getMilliseconds());
  ctxsolar.translate(0, 28.5);
  ctxsolar.drawImage(moon, -3.5, -3.5);
  ctxsolar.restore();

  ctxsolar.restore();

  ctxsolar.beginPath();
  ctxsolar.arc(150, 150, 105, 0, Math.PI * 2, false); // Earth orbit
  ctxsolar.stroke();

  ctxsolar.drawImage(sun, 0, 0, 300, 300);

  window.requestAnimationFrame(drawsolargalaxy);
}



//时间
let clock = () => {
  let now = new Date();
  let ctxtime = document.getElementById('time').getContext('2d');
  ctxtime.save();
  ctxtime.clearRect(0, 0, 150, 150);
  ctxtime.translate(75, 75);
  ctxtime.scale(0.4, 0.4);
  ctxtime.rotate(-Math.PI / 2);
  ctxtime.strokeStyle = "black";
  ctxtime.fillStyle = "white";
  ctxtime.lineWidth = 8;
  ctxtime.lineCap = "round";

  // Hour marks
  ctxtime.save();
  for (let i = 0; i < 12; i++) {
    ctxtime.beginPath();
    ctxtime.rotate(Math.PI / 6);
    ctxtime.moveTo(100, 0);
    ctxtime.lineTo(120, 0);
    ctxtime.stroke();
  }
  ctxtime.restore();

  // Minute marks
  ctxtime.save();
  ctxtime.lineWidth = 5;
  for (i = 0; i < 60; i++) {
    if (i % 5 != 0) {
      ctxtime.beginPath();
      ctxtime.moveTo(117, 0);
      ctxtime.lineTo(120, 0);
      ctxtime.stroke();
    }
    ctxtime.rotate(Math.PI / 30);
  }
  ctxtime.restore();

  let sec = now.getSeconds();
  let min = now.getMinutes();
  let hr = now.getHours();
  hr = hr >= 12 ? hr - 12 : hr;

  ctxtime.fillStyle = "black";

  // write Hours
  ctxtime.save();
  ctxtime.rotate(hr * (Math.PI / 6) + (Math.PI / 360) * min + (Math.PI / 21600) * sec)
  ctxtime.lineWidth = 14;
  ctxtime.beginPath();
  ctxtime.moveTo(-20, 0);
  ctxtime.lineTo(80, 0);
  ctxtime.stroke();
  ctxtime.restore();

  // write Minutes
  ctxtime.save();
  ctxtime.rotate((Math.PI / 30) * min + (Math.PI / 1800) * sec)
  ctxtime.lineWidth = 10;
  ctxtime.beginPath();
  ctxtime.moveTo(-28, 0);
  ctxtime.lineTo(112, 0);
  ctxtime.stroke();
  ctxtime.restore();

  // Write seconds
  ctxtime.save();
  ctxtime.rotate(sec * Math.PI / 30);
  ctxtime.strokeStyle = "#D40000";
  ctxtime.fillStyle = "#D40000";
  ctxtime.lineWidth = 6;
  ctxtime.beginPath();
  ctxtime.moveTo(-30, 0);
  ctxtime.lineTo(83, 0);
  ctxtime.stroke();
  ctxtime.beginPath();
  ctxtime.arc(0, 0, 10, 0, Math.PI * 2, true);
  ctxtime.fill();
  ctxtime.beginPath();
  ctxtime.arc(95, 0, 10, 0, Math.PI * 2, true);
  ctxtime.stroke();
  ctxtime.fillStyle = "rgba(0,0,0,0)";
  ctxtime.arc(0, 0, 3, 0, Math.PI * 2, true);
  ctxtime.fill();
  ctxtime.restore();

  ctxtime.beginPath();
  ctxtime.lineWidth = 14;
  ctxtime.strokeStyle = '#325FA2';
  ctxtime.arc(0, 0, 142, 0, Math.PI * 2, true);
  ctxtime.stroke();

  ctxtime.restore();

  window.requestAnimationFrame(clock);
}




//鼠标追踪
var cn;
//= document.getElementById('cw');
var c;
var u = 10;
const m = {
    x: innerWidth / 2,
    y: innerHeight / 2
};
window.onmousemove = function(e) {
    m.x = e.clientX;
    m.y = e.clientY;

}
function gc() {
    var s = "0123456789ABCDEF";
    var c = "#";
    for (var i = 0; i < 6; i++) {
        c += s[Math.ceil(Math.random() * 15)]
    }
    return c
}
var a = [];
window.onload = function myfunction() {
    cn = document.getElementById('mousedect');
    c = cn.getContext('2d');

    for (var i = 0; i < 10; i++) {
        var r = 30;
        var x = Math.random() * (innerWidth - 2 * r) + r;
        var y = Math.random() * (innerHeight - 2 * r) + r;
        var t = new ob(innerWidth / 2,innerHeight / 2,5,"red",Math.random() * 200 + 20,2);
        a.push(t);
    }
    //cn.style.backgroundColor = "#700bc8";

    c.lineWidth = "2";
    c.globalAlpha = 0.5;
    resize1();
    anim()
}
window.onresize = function() {

    resize1();

}
function resize1() {
    cn.height = innerHeight;
    cn.width = innerWidth;
    for (var i = 0; i < 101; i++) {
        var r = 30;
        var x = Math.random() * (innerWidth - 2 * r) + r;
        var y = Math.random() * (innerHeight - 2 * r) + r;
        a[i] = new ob(innerWidth / 2,innerHeight / 2,4,gc(),Math.random() * 200 + 20,0.02);

    }
    //  a[0] = new ob(innerWidth / 2, innerHeight / 2, 40, "red", 0.05, 0.05);
    //a[0].dr();
}
function ob(x, y, r, cc, o, s) {
    this.x = x;
    this.y = y;
    this.r = r;
    this.cc = cc;
    this.theta = Math.random() * Math.PI * 2;
    this.s = s;
    this.o = o;
    this.t = Math.random() * 150;

    this.o = o;
    this.dr = function() {
        const ls = {
            x: this.x,
            y: this.y
        };
        this.theta += this.s;
        this.x = m.x + Math.cos(this.theta) * this.t;
        this.y = m.y + Math.sin(this.theta) * this.t;
        c.beginPath();
        c.lineWidth = this.r;
        c.strokeStyle = this.cc;
        c.moveTo(ls.x, ls.y);
        c.lineTo(this.x, this.y);
        c.stroke();
        c.closePath();

    }
}
function anim() {
    requestAnimationFrame(anim);
    c.fillStyle = "rgba(0,0,0,0.05)";
    c.fillRect(0, 0, cn.width, cn.height);
    a.forEach(function(e, i) {
        e.dr();
    });

}



//小球
var ballcanvas = document.getElementById('ballcanva');
var ctxball = ballcanvas.getContext('2d');
var raf;
var running = false;

var ball = {
  x: 100,
  y: 100,
  vx: 5,
  vy: 1,
  radius: 25,
  color: 'blue',
  draw: function() {
    ctxball.beginPath();
    ctxball.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
    ctxball.closePath();
    ctxball.fillStyle = this.color;
    ctxball.fill();
  }
};

function clear() {
  ctxball.fillStyle = 'rgba(255,255,255,0.3)';
  ctxball.fillRect(0,0,ballcanvas.width,ballcanvas.height);
}

function draw() {
  clear();
  ball.draw();
  ball.x += ball.vx;
  ball.y += ball.vy;

  if (ball.y + ball.vy > ballcanvas.height || ball.y + ball.vy < 0) {
    ball.vy = -ball.vy;
  }
  if (ball.x + ball.vx > ballcanvas.width || ball.x + ball.vx < 0) {
    ball.vx = -ball.vx;
  }

  raf = window.requestAnimationFrame(draw);
}

ballcanvas.addEventListener('mousemove', function(e){
  if (!running) {
    clear();
    ball.x = e.offsetX;
    ball.y = e.offsetY;
    ball.draw();
  }
});

ballcanvas.addEventListener('click',function(e){
  if (!running) {
    raf = window.requestAnimationFrame(draw);
    running = true;
  }
});

ballcanvas.addEventListener('mouseout', function(e){
  window.cancelAnimationFrame(raf);
  running = false;
});


//全景照片
var imgall = new Image();
var ctxpic = document.getElementById('picture').getContext('2d');

// User Variables - customize these to change the image being scrolled, its
// direction, and the speed.

imgall.src = 'image/YNP.jpg';
var CanvasXSize = 800;
var CanvasYSize = 200;
var speed = 30; // lower is faster
var scale = 1.05;
var y = -4.5; // vertical offset

// Main program

var dx = 0.75;
var imgW;
var imgH;
var x = 0;
var clearX;
var clearY;

imgall.onload = function() {
    imgW = imgall.width * scale;
    imgH = imgall.height * scale;

    if (imgW > CanvasXSize) {
        // image larger than canvas
        x = CanvasXSize - imgW;
    }
    if (imgW > CanvasXSize) {
        // image width larger than canvas
        clearX = imgW;
    } else {
        clearX = CanvasXSize;
    }
    if (imgH > CanvasYSize) {
        // image height larger than canvas
        clearY = imgH;
    } else {
        clearY = CanvasYSize;
    }

    // get canvas context
    ctxpic = document.getElementById('picture').getContext('2d');

    // set refresh rate
    return setInterval(picturedraw, speed);
}

function picturedraw() {
    ctxpic.clearRect(0, 0, clearX, clearY); // clear the canvas

    // if image is <= Canvas Size
    if (imgW <= CanvasXSize) {
        // reset, start from beginning
        if (x > CanvasXSize) {
            x = -imgW + x;
        }
        // draw additional image1
        if (x > 0) {
            ctxpic.drawImage(imgall, -imgW + x, y, imgW, imgH);
        }
        // draw additional image2
        if (x - imgW > 0) {
            ctxpic.drawImage(imgall, -imgW * 2 + x, y, imgW, imgH);
        }
    }

    // image is > Canvas Size
    else {
        // reset, start from beginning
        if (x > (CanvasXSize)) {
            x = CanvasXSize - imgW;
        }
        // draw aditional image
        if (x > (CanvasXSize-imgW)) {
            ctxpic.drawImage(imgall, x - imgW + 1, y, imgW, imgH);
        }
    }
    // draw image
    ctxpic.drawImage(imgall, x, y,imgW, imgH);
    // amount to move
    x += dx;
}



//human
const config = {
  src: 'image//open-peeps-sheet.png',
  rows: 15,
  cols: 7 };


// UTILS

const randomRange = (min, max) => min + Math.random() * (max - min);

const randomIndex = array => randomRange(0, array.length) | 0;

const removeFromArray = (array, i) => array.splice(i, 1)[0];

const removeItemFromArray = (array, item) => removeFromArray(array, array.indexOf(item));

const removeRandomFromArray = array => removeFromArray(array, randomIndex(array));

const getRandomFromArray = (array) =>
array[randomIndex(array) | 0];


// TWEEN FACTORIES

const resetPeep = ({ stage, peep }) => {
  const direction = Math.random() > 0.5 ? 1 : -1;
  // using an ease function to skew random to lower values to help hide that peeps have no legs
  const offsetY = 100 - 250 * gsap.parseEase('power2.in')(Math.random());
  const startY = stage.height - peep.height + offsetY;
  let startX;
  let endX;

  if (direction === 1) {
    startX = -peep.width;
    endX = stage.width;
    peep.scaleX = 1;
  } else {
    startX = stage.width + peep.width;
    endX = 0;
    peep.scaleX = -1;
  }

  peep.x = startX;
  peep.y = startY;
  peep.anchorY = startY;

  return {
    startX,
    startY,
    endX };

};

const normalWalk = ({ peep, props }) => {
  const {
    startX,
    startY,
    endX } =
  props;

  const xDuration = 10;
  const yDuration = 0.25;

  const tl = gsap.timeline();
  tl.timeScale(randomRange(0.5, 1.5));
  tl.to(peep, {
    duration: xDuration,
    x: endX,
    ease: 'none' },
  0);
  tl.to(peep, {
    duration: yDuration,
    repeat: xDuration / yDuration,
    yoyo: true,
    y: startY - 10 },
  0);

  return tl;
};

const walks = [
normalWalk];


// CLASSES

class Peep {
  constructor({
    image,
    rect })
  {
    this.image = image;
    this.setRect(rect);

    this.x = 0;
    this.y = 0;
    this.anchorY = 0;
    this.scaleX = 1;
    this.walk = null;
  }

  setRect(rect) {
    this.rect = rect;
    this.width = rect[2];
    this.height = rect[3];

    this.drawArgs = [
    this.image,
    ...rect,
    0, 0, this.width, this.height];

  }

  render(ctx1) {
    ctx1.save();
    ctx1.translate(this.x, this.y);
    ctx1.scale(this.scaleX, 1);
    ctx1.drawImage(...this.drawArgs);
    ctx1.restore();
  }}


// MAIN

const img = document.createElement('img');
img.onload = init;
img.src = config.src;

const humancanvas = document.querySelector('#humancanvas');
const ctx1 = humancanvas.getContext('2d');

const stage = {
  width: 0,
  height: 0 };


const allPeeps = [];
const availablePeeps = [];
const crowd = [];

function init() {
  createPeeps();

  // resize also (re)populates the stage
  resize();

  gsap.ticker.add(render);
  window.addEventListener('resize', resize);
}

function createPeeps() {
  const {
    rows,
    cols } =
  config;
  const {
    naturalWidth: width,
    naturalHeight: height } =
  img;
  const total = rows * cols;
  const rectWidth = width / rows;
  const rectHeight = height / cols;

  for (let i = 0; i < total; i++) {
    allPeeps.push(new Peep({
      image: img,
      rect: [
      i % rows * rectWidth,
      (i / rows | 0) * rectHeight,
      rectWidth,
      rectHeight] }));


  }
}

function resize() {
  stage.width = humancanvas.clientWidth;
  stage.height = humancanvas.clientHeight;
  humancanvas.width = stage.width * devicePixelRatio;
  humancanvas.height = stage.height * devicePixelRatio;

  crowd.forEach(peep => {
    peep.walk.kill();
  });

  crowd.length = 0;
  availablePeeps.length = 0;
  availablePeeps.push(...allPeeps);

  initCrowd();
}

function initCrowd() {
  while (availablePeeps.length) {
    // setting random tween progress spreads the peeps out
    addPeepToCrowd().walk.progress(Math.random());
  }
}

function addPeepToCrowd() {
  const peep = removeRandomFromArray(availablePeeps);
  const walk = getRandomFromArray(walks)({
    peep,
    props: resetPeep({
      peep,
      stage }) }).

  eventCallback('onComplete', () => {
    removePeepFromCrowd(peep);
    addPeepToCrowd();
  });

  peep.walk = walk;

  crowd.push(peep);
  crowd.sort((a, b) => a.anchorY - b.anchorY);

  return peep;
}

function removePeepFromCrowd(peep) {
  removeItemFromArray(crowd, peep);
  availablePeeps.push(peep);
}

function render() {
  humancanvas.width = humancanvas.width;
  ctx1.save();
  ctx1.scale(devicePixelRatio, devicePixelRatio);

  crowd.forEach(peep => {
    peep.render(ctx1);
  });

  ctx1.restore();
}



//赋予元素！

let square = document.getElementById('square');
let simailu = document.getElementById('simailu');
let solargalaxy = document.getElementById('solargalaxy');
let time = document.getElementById('time');
let mousedect = document.getElementById('mousedect');
let ballcanva = document.getElementById('ballcanva');
let picture = document.getElementById('picture');



//执行！

simailu.onload = drawface();
square.onload = drawsquare();
solargalaxy.onload = solarinit();
time.onload = clock();
ballcanva.onload = ball.draw();
picture.onload = picturedraw();

//humancanvas.onload = inithuman();